using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace MIS.EN.WebDav
{
    internal static class WebDavCollBlobHelper
    {
        public static void PersistCollBlob(string collBlob, string userId, string folderType)
        {
            if (collBlob != null && collBlob.Length > 0)
            {
                // Persist it to the file system for now
                string fileName = WebDavCollBlobHelper.GetCollBlobFileName(userId, folderType);
                string directoryName = WebDavCollBlobHelper.GetCollBlobDirectoryName(folderType);
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }
                using (StreamWriter writer = new StreamWriter(File.Open(fileName, FileMode.Create, FileAccess.Write)))
                {
                    writer.Write(collBlob);
                }
            }
        }

        private static string GetCollBlobFileName(string userId, string folderType)
        {
            return WebDavCollBlobHelper.GetCollBlobDirectoryName(folderType) + "\\" + userId + ".dat";
        }

        private static string GetCollBlobDirectoryName(string folderType)
        {
            return System.Environment.CurrentDirectory + "\\MIS.EN\\CollBlobs\\" + folderType;
        }

        public static string RetrieveCollBlob(string userId, string folderType)
        {
            string collBlob = string.Empty;
            if (File.Exists(WebDavCollBlobHelper.GetCollBlobFileName(userId, folderType)))
            {
                using (StreamReader reader = new StreamReader(File.Open(WebDavCollBlobHelper.GetCollBlobFileName(userId, folderType),
                    FileMode.Open, FileAccess.Read)))
                {
                    collBlob = reader.ReadToEnd();
                }
            }
            return collBlob;
        }
    }
}
